import beautiful.butterfly.execute_engine.CallableContext;
import beautiful.butterfly.execute_engine.CallableObject;
import beautiful.butterfly.execute_engine.ExecuteEngine;
import beautiful.butterfly.execute_engine.TimeUnit;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;


public class test {
    public static void main(String[] args) throws InterruptedException {


        final CallableObject callableObject = new CallableObject() {
            @Override
            public Object doTask() throws Exception {
                CallableContext callableContext = this.getCallableContext();
                while (true) {
                    //System.out.println(callableContext + "callableContext"); checkWhetherNeedInterruptIfRunning callableContext is null ?
                    System.out.println("doing" + callableContext.isRun + "isRun");
                    System.out.println(callableContext + "callableContext");
                    callableContext.checkRun();
                    callableContext.checkWhetherNeedInterruptIfRunning();
                    if (1 == 0) {
                        break;
                    }
                }
                callableContext.countDown();
                return null;
            }
        };
        ExecutorService executorService = Executors.newCachedThreadPool();
        //
        Future future = executorService.submit(callableObject);
        CallableContext callableContext = new CallableContext(ExecuteEngine.callableToCallableContextMap, callableObject, future);
        callableContext.setSequence();
        callableObject.setCallableContext(callableContext);//CallableContext创建好了再进行设置callableContext
        ExecuteEngine.callableToCallableContextMap.put(callableObject, callableContext);
        TimeUnit.sleepNSecondsIgnoreInterruptedException(30);
        callableContext.await();
        //callableToCallableContextMap.get(callableObject).setNeedInterruptIfRunning(true);
        //future.cancel(true); 只能够在没有启动任务的时候进行取消才有效，经过测试
        //因为存在上面的代码await(),所以执行引擎的代码必须和控制代码分开，才能保证有效.
        while (true) {
            ExecuteEngine.callableToCallableContextMap.get(callableObject).setNotRun();
            TimeUnit.sleepNSecondsIgnoreInterruptedException(30);
            ExecuteEngine.callableToCallableContextMap.get(callableObject).setRun();

        }
    }
}
